﻿using System;
using System.Linq;
using System.Windows.Messaging;

namespace Remoting.Reactive.Windowing
{
    public class LocalMessageSenderObservable : ILocalMessageSenderObservable
    {
        private readonly LocalMessageSender _localMessageSender;

        public LocalMessageSenderObservable(LocalMessageSender localMessageSender)
        {
            Guard.Requires<ArgumentNullException>(localMessageSender != null);
            _localMessageSender = localMessageSender;
        }

        public IObservable<ISendCompleted> Send(string message)
        {
            Guard.Requires<ArgumentException>(message != null);
            var connectable = Observable.FromEvent<SendCompletedEventArgs>(
                eh => _localMessageSender.SendCompleted += eh,
                eh => _localMessageSender.SendCompleted -= eh)
                .Select(evt => new SendCompleted(evt.EventArgs) as ISendCompleted)
                .Take(1)
                .Prune();
            connectable.Connect();
            return connectable.AsObservable();
        }

        public string ReceiverName
        {
            get { return _localMessageSender.ReceiverName; }
        }

        public string ReceiverDomain
        {
            get { return _localMessageSender.ReceiverDomain; }
        }
    }
}
